var imgUrl = 'http://app.jfl138.com/';
// var imgUrl = 'http://shangjing.wangpaisoft.com/';
// var serverUrl = 'http://app.jfl138.com/yii/web/api/';
// var mainService="http://192.168.8.109/";
var mainService="http://app.jfl138.com/";

var serverUrl = mainService+'yii/web/api/';
var serverUrlAfter= mainService+'yii/web/';

var AliPayBack="http://app.jfl138.com/pay/alipay/notify_su_shangjing.php";

//解决ios和安卓头部兼容的高度
// IosAndroid_height=api.systemType=='ios'?20.0:0.0;
//引入md5js文件
// document.write('<script language="javascript" src="../script/md5.min.js"><\/script>');
//重新获取缓存
function getUserId() {
    userid = $api.getStorage('user_id');
    if (typeof (userid) == "undefined") {
        userid = 0;
    }
    return userid;
}
function getStorageAll() {
    user_id = $api.getStorage('user_id');
    // user_password = $api.getStorage('user_password');
    user_mobile = $api.getStorage('user_mobile');
    user_name = $api.getStorage('user_name');
    nick_name = $api.getStorage('nick_name');
    avatar = $api.getStorage('avatar');
    usqrcode = $api.getStorage('usqrcode');
    seqrcode = $api.getStorage('seqrcode');
    user_type = $api.getStorage('user_type');
    group_id = $api.getStorage('group_id');
}

function getUserInfo() {
    // alert("ds")
    getStorageAll();
    user_id = $api.getStorage('user_id');
    if (!user_id) return false;
    // alert("dc")
    // user_password = $api.getStorage('user_password');
    // member_type = $api.getStorage('member_type');
    // user_name = $api.getStorage('user_name');
    // alert(user_password+"dd"+user_id+"d"+)
    if (avatar != "") {
        $(".touxiang").css({"background-image": "url(" + imgUrl + avatar + ")"});
    }


    // return false;
    var url = "user_ajax.ashx?action=get_user_info";
    var data = {};
    data.user_id = user_id;
    ajaxRequest(url, 'post', data, function (ret, err) {
        $("body").find(".stat_field").each(function () {
            var info_id = $(this).attr("id");
            // alert(info_id)
            $(this).text(ret.msg[info_id])
            if (info_id == "sex") {
                var sex = ret.msg[info_id] == "密" ? "保密" : ret.msg[info_id];
                $(this).text(sex)
            }
        })
        if (ret.msg.avatar != "") {
            $(".touxiang").css({"background-image": "url(" + imgUrl + ret.msg.avatar + ")"});
        }
        // api.refreshHeaderLoadDone();
        api.sendEvent({
            name: "getUserInfoFinish",
            extra: {
                key: true
            }
        })

    });

}
function showLoginInfo() {
    //
    // $("#vmoney_total").text(user_money_data.vmoney_total);
    // $("#vmoney_user").text(user_money_data.vmoney_user);
    // $("#vmoney_returned").text(user_money_data.vmoney_returned);
    // $("#money_withdrawal").text(user_money_data.money_withdrawal);
    // $("#vmoney_supplier").text(user_money_data.vmoney_supplier);


    /******************/
    // $("#jifen_left").text(jifen_left);
    // $("#jifen_returned").text(jifen_returned);
    // $("#amount_total").text(amount_total);
    // $("#money_thismonth").text(money_thismonth);
    // $("#money_unwithdrawn").text(money_unwithdrawn);
    // $("#money_withdrawn").text(money_withdrawn);
    // $("#money_total").text(money_total);
    // $("#amount_today").text(amount_today);
    // $(".name").text(user_name);
    // $("#shared_grade").text(userInfo_data.shared_grade);
    // $(".touxiang").css({"background-image": "url(" + avatar + ")"});
    // $("#agent_money_unwithdrawn").text((money_total - money_unwithdrawn).toFixed(2));
    // $("#yiti_jifen_returned").text(jifen_withdrawn);


}

//重新登录监听
function sendReGetMyInfo() {
    api.sendEvent({
        name: 'reGetMyInfo',
        extra: {
            key: 'true'
        }
    });
}
//判断是否登录
function isLogin() {
    getStorageAll();
    if (!user_id) {
//        if (!user_id ) {
        setTimeout(function () {
            api.openWin({
                name: 'loginPass_win',
                url: 'loginPass_win.html'
            })
        }, 1000)
        return false;
    }
}
//两次退出
var first = null;
function back() {
    api.addEventListener({
        name: 'keyback'
    }, function (ret, err) {
        if (!first) {
            first = new Date().getTime();
            api.toast({
                msg: '再按一次回到桌面',
                duration: 1500,
                location: 'bottom'
            });
            setTimeout(function () {
                first = null;
            }, 1500);
        } else {
            if (new Date().getTime() - first < 1500) {
                //回到系统桌面
                api.toLauncher();
            }
        }
    });
}

//关闭窗体
function closeWin() {
    api.closeWin();
}

//打开窗体-无提示
function openToTwo(winname) {
    api.openWin({
        name: winname,
        url: '' + winname + '.html',
        // delay: 300,
        vScrollBarEnabled: false
    });
}

//打开窗体-有提示
function openTo(winname) {
    api.toast({
        msg: '请先登录',
        duration: 2000,
        location: 'bottom'
    });
    api.openWin({
        name: winname,
        url: '' + winname + '.html',
        // delay: 300
    });
}

//打开窗体-判断登录
function openWin(name) {
    getStorageAll();
    if (!user_id) {
        api.openWin({
            name: 'login_win',
            url: 'login_win.html',
            // delay: 300
        })
    } else {
        api.openWin({
            name: '' + name + '',
            url: '' + name + '.html',
            // delay: 300
        })
    }
}

//切换帐号
function changeAccount() {
    $api.clearStorage();
    api.sendEvent({
        name: 'reGetMyInfo',
        extra: {
            key: 'true'
        }
    });
    api.openWin({
        name: 'login_win',
        url: 'login_win.html',
        // delay: 300
    })
}

//清除缓存
function clearCache() {
    api.clearCache();
    api.toast({
        msg: '清除成功',
        duration: 2000,
        location: 'bottom'
    });
}
function getTimeStampUrl() {
    getStorageAll()
    var timeStamp = Date.parse(new Date())
    url = "?requid=" + user_id + "&reqtime=" + timeStamp + "&key=" + md5(timeStamp + user_password);
    return url;
}
function ajaxRequest(url, method, datas, successCallBack, errorCallback) {
    getStorageAll()
    // if (user_id) {
    //     url += getTimeStampUrl();
    // }
    if (api.connectionType == 'none') {
        api.toast({
            msg: '当前网络不可用，请检查网络配置'
        });
    } else {
        api.ajax({
                url: serverUrl + url,
                method: method,
                cache: false,
                timeout: 60,
                dataType: 'json',
                data: {
                    values: datas
                }
            }, function (ret, err) {
                if (ret.status == 0) {
                    api.hideProgress();
                    hideLoading();
                    if (!errorCallback) {
                        if (ret.error_code == 20002) {
                            $api.clearStorage();
                            window.setTimeout(function () {
                                goToHome(0);
                            }, 1000);
                        }
                        api.toast({
                            msg: ret.msg
                        });
                    } else {
                        errorCallback(ret)
                    }
                } else {
                    successCallBack(ret, err)
                }
            }
        );
    }
}

var myLon = 113.23, myLat = 23.16;
function getLocation(callBack) {
    // var baiduLocation = api.require('baiduLocation');
    // baiduLocation.startLocation({
    //     accuracy: '500m',
    //     filter: 1,
    //     autoStop: true
    // }, function (ret, err) {
    //     var sta = ret.status;
    //     var lat = ret.latitude;
    //     var lon = ret.longitude;
    //     var location = '' + lat + ',' + lon + '';
    //     var ak = '4880fdc9318f40e4afac92629b9bbb66';
    //     api.ajax({
    //         url: 'http://api.map.baidu.com/geocoder/v2/?ak=' + ak + '&location=' + location + '&output=json&pois=0',
    //         method: 'get',
    //         timeout: 60,
    //         dataType: 'json',
    //         data: {}
    //     }, function (ret, err) {
    //         //if (ret.status == 0) {
    //         //	var address = ret.result.formatted_address;
    //         //}
    //         callBack(ret, err);
    //     });
    // })


    //下面最新的
    bMap = api.require('bMap');
    bMap.getLocationServices(function (ret, err) {
        if (!ret.enable) {
            api.toast({
                msg: "未开启定位功能,默认广州市",
                duration: 2000
            })
        } else {
            bMap.getLocation({
                accuracy: '100m',
                autoStop: true,
                filter: 1
            }, function (ret, err) {
                if (ret.status) {
                    myLon = ret.lon;
                    myLat = ret.lat;
                    setUserLocation(myLat, myLon)


                    $api.setStorage('location_lon', '' + ret.lon + '');//经度
                    $api.setStorage('location_lat', '' + ret.lat + '');//维度
                } else {
                    api.toast({
                        msg: "获取定位出错,默认广州市",
                        duration: 2000
                    })
                }
            });
        }
    });

}
function setUserLocation(lat, lon) {
    var url = 'user_ajax.ashx?action=updateLocation';
    var data = {};
    data.user_id = user_id;
    data.lat = lat;
    data.lon = lon;
    ajaxRequest(url, 'post', data, function (ret, err) {
        // alert(JSON.stringify(ret))
    });
}
//根据经纬度计算距离
function getTheDisance(lat1, lng1, lat2, lng2) {
    var radLat1 = getRad(lat1);
    var radLat2 = getRad(lat2);

    var a = radLat1 - radLat2;
    var b = getRad(lng1) - getRad(lng2);

    var s = 2 * Math.asin(Math.sqrt(Math.pow(Math.sin(a / 2), 2) + Math.cos(radLat1) * Math.cos(radLat2) * Math.pow(Math.sin(b / 2), 2)));
    s = s * EARTH_RADIUS;
    s = Math.round(s * 10000) / 10000.0;
    if ((s / 1000) > 1000) {
        s = ">999"
    } else {
        s = (s / 1000).toFixed(1)
    }
    return s;

}
var EARTH_RADIUS = 6378137.0;    //单位M
var PI = Math.PI;
function getRad(d) {
    return d * PI / 180.0;
}

function showLoading(time) {
    var body = $api.dom("body");
    var loading = $api.byId("loading");
    if (!loading) {
        $api.append(body, '<div class="aui-loading" id="loading"></div>');
        if (time && time > 0) {
            //如果有时间传进来就定时隐藏
            $api.remove(loading);
        }
    }
}

function hideLoading() {
    var loading = $api.byId("loading");
    setTimeout(function () {
        $api.remove(loading);
    }, 500);

}

//BMAP获取地理位置
function updateLocation() {
    //更新位置信息
    var map = api.require('bMap');
    map.getLocation({
        accuracy: '100m',
        autoStop: true,
        filter: 1
    }, function (ret, err) {
        if (ret.status) {
            var data = {};
            var lat = ret.lat;
            var lon = ret.lon;
            //更新缓存
            $api.setStorage('lat', '' + lat + '');
            $api.setStorage('lon', '' + lon + '');
            data['lat'] = lat;
            data['lon'] = lon;
            data['user_id'] = $api.getStorage('user_id');
            var url = 'user_ajax.ashx?action=updateLocation';
            ajaxRequest(url, 'post', data, function (ret, err) {
                //alert(JSON.stringify(ret.msg));
            });
        } else {
            alert(err.code);
        }
    })
}

function formatDate(time) {
    //var newTime = time.substring(0,10);
    var date = new Date(time * 1000);
    var hour = date.getHours();
    var minute = date.getMinutes();
    var second = date.getSeconds();
    return hour + ':' + minute;
}


function openPicker(dateType) {
    var dateType = $api.byId('' + dateType + '');
    if (api.systemType == 'android') {
        api.openPicker({
            type: 'date',
            title: '选择时间'
        }, function (ret, err) {
            var year = ret.year;
            var month = ret.month;
            var day = ret.day;
            var value1 = year + '-' + month + '-' + day;
            $api.val(dateType, '' + value1 + '');
        });
    } else if (api.systemType == 'ios') {
        api.openPicker({
            type: 'date_time',
            title: '选择时间'
        }, function (ret, err) {
            var year = ret.year;
            var month = ret.month;
            var day = ret.day;
            var hour = ret.hour;
            var minute = ret.minute;
            var value1 = year + '-' + month + '-' + day;
            $api.val(dateType, '' + value1 + '');
        });
    }
}

//微信支付接口
// function wxpay(subject, body, amount, tradeNO) {
/**
 *
 * @param appid 支付appid
 * @param noncestr
 * @param package
 * @param partnerid 商家id
 * @param prepayid  微信返回的支付orderid
 * @param sign
 * @param timestamp
 */
function wxpay(name,money,orderNo,detail) {
    var wxPay = api.require('wxPay');
    hideLoading()
    wxPay.config({
        apiKey: 'wxc08740ac8dab5350',
        mchId: '1483221072',
        partnerKey: 'sewiosdfk3idjjkjdfd399568jdclwle',
        notifyUrl: WxPayBack
    }, function (ret, err) {
        if (ret.status) {
            //alert("配置成功！" + err.code);
            wxPay.pay({
                description: name, //简要描述
                totalFee: money*100,     //订单金额
                tradeNo: orderNo,     //订单编号
                detail: detail,         //明细列表
                feeType: 'CNY'
            }, function (ret, err) {
                if (ret.status) {

                    api.sendEvent({
                        name: 'reGetMyInfo',
                        extra: {
                            key: 'true'
                        }
                    })
                    api.toast({
                        msg: "支付成功"
                    })
                    failClose()
                    // sendReGetMyInfo();
                    // notify_url(tradeNO);
                } else {
                    // alert("error" + JSON.stringify(err));
                    // alert("msg:" + err.msg);
                    if(err.code=="-2"){
                        api.toast({
                            msg: '已取消支付',
                            location: 'middle'
                        })
                    }else{
                        api.toast({
                            msg: '支付失败，请联系管理员',
                            location: 'middle'
                        })
                    }
                }
            })
        } else {
            //alert("配置失败 error" + err.code);
        }
    })

    // wxPay.config({
    //     apiKey: 'wx1310abcc2bdcac76',
    //     mchId: '1401969902',
    //     partnerKey: '38jfjksfu8kk3jdjfdjf3jkdjf34jjfd',
    //     notifyUrl: 'http://riyu.21dianshang.com/tools/weixinpay/return_url.aspx'
    // }, function (ret, err) {
    //     if (ret.status) {
    //         //alert("配置成功！" + err.code);
    //         wxPay.pay({
    //             description: subject, //简要描述
    //             totalFee: amount,     //订单金额
    //             tradeNo: tradeNO,     //订单编号
    //             detail: body,         //明细列表
    //             feeType: 'CNY'
    //         }, function (ret, err) {
    //             if (ret.status) {
    //                 api.toast({
    //                     msg: '支付成功',
    //                     location: 'middle'
    //                 });
    //                 sendReGetMyInfo();
    //                 notify_url(tradeNO);
    //             } else {
    //                 //alert("error" + err.code);
    //                 alert("msg:" + err.msg);
    //                 api.toast({
    //                     msg: '支付失败',
    //                     location: 'middle'
    //                 })
    //             }
    //         })
    //     } else {
    //         //alert("配置失败 error" + err.code);
    //     }
    // })
}

//支付宝接口
function aliPay(subject, body, amount, tradeNO) {
    var obj = api.require('aliPay');
    obj.pay({
        partner: '2088521533072680',
        seller: 'zgfz1688@163.com',
        rsaPriKey: 'MIICdwIBADANBgkqhkiG9w0BAQEFAASCAmEwggJdAgEAAoGBANy7iNSahQiIxbSiTQwldMMTAflFsP/+6tp9Dn134wstExY6cTLYyNqZOq87cZBOyRuv1n3QNUNJcgrZoAUaCLvvcgXC11ZfXRTY3URh1HDY9q5rv1nofLQQ1YAugGu149YVu7fvoQ9z/HMNdFntgb2CipwtfQAPqMxG76mQ9ulLAgMBAAECgYEA0EOVX9uHR70cpUk5Xwt8No6ZnyNVVMSlvI6f/FwAecwGpUNxCOOn5zEKQMnaZakgcSIgQ8cOajVDB9+77vRYZZExAo72VZhaJ+aE0WHLnW4blpkZPCxTENDHjnKhl9IH1o8kDOXMzP8F7BDfFUymI8v0IZuSs5A226o7oy4Gv5ECQQD2dJJESMTQShwKpXVFy9dhyr6isGT1CaLP+f+Tm7cMhp+Cho8sNEsp5qI3SttMntplp6Y5FvpXjDYbKzTVD49DAkEA5UfwobK2ixJbrffam6egSymuejY8i/ONoz1zbB+BRc9LQTHjcFkFAeQwSUm5ZtdI7s7gA33rC5G2mHA2aTxJWQJBAI69Qz2jO8I7OfR8kehjwBHWgATvzvkQpKh57alLJYButBG/50o9206gUlFd3JeK5Yi8yYwFH+b2wRuJMac4xMsCQA/YPd/eytCnjyBhnYDeP6ySD9WwQ9TkGuiqCXzyXGunnKq/uNj9vePYkiGub5qUzBx8vWxgWkrtYfH85zW0jdkCQHAa+lZTk4m33YndZgEsMscvxpVbzbiNr87aBKy1OJHjjQ1jRbnkWVXJG/7HuCFflY/XfPqp+GEcjb2J5EOs0to=',
        rsaPubKey: 'MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQDcu4jUmoUIiMW0ok0MJXTDEwH5RbD//urafQ59d+MLLRMWOnEy2MjamTqvO3GQTskbr9Z90DVDSXIK2aAFGgi773IFwtdWX10U2N1EYdRw2Paua79Z6Hy0ENWALoBrtePWFbu376EPc/xzDXRZ7YG9goqcLX0AD6jMRu+pkPbpSwIDAQAB',
        subject: '1000879', //订单名
        body: '1000879', //订单描述
        amount: 55, //金额
//            amount: 0.01, //金额
        tradeNO: 55, //订单编号
        notifyURL: serverUrl + 'Order/aliNotify'
    }, function (ret, err) {
        if (ret.code == 9000) {
            var data = {};
            var url = 'Order/orderStatusModify/userName/' + user_name + '/orderId/' + orderId + '/status/2/type/1';
            ajaxRequest(url, 'post', data, function (ret, err) {
                if (ret.status == 1) {
                    $(".pickerToTop").css({"display": "none"});
                    $(".result").css({"display": "block"});
                    $(".bodyLayer").hide();
                    $("body").css({"background": "#fff"})
                    updateOrderNum();
                } else {
                    api.toast({
                        msg: ret.msg,
                        duration: 2000,
                        location: 'bottom'
                    })
                }
            })
        } else {
            //9000：支付成功
            //4000：系统异常
            //4001：数据格式不正确
            //4003：该用户绑定的支付宝账户被冻结或不允许支付
            //4004：该用户已解除绑定
            //4005：绑定失败或没有绑定
            //4006：订单支付失败
            //4010：重新绑定账户
            //6000：支付服务正在进行升级操作
            //6001：用户中途取消支付操作
            //0001：缺少商户配置信息（商户id，支付公钥，支付密钥）
            //0002：缺少参数（subject、body、amount、tradeNO）
            //0003：签名错误（公钥私钥错误）
            var textMsg = "";
            switch (parseInt(ret.code)) {
                case 4000:
                    textMsg = "系统异常";
                    break;
                case 4001:
                    textMsg = "数据格式不正确";
                    break;
                case 4003:
                    textMsg = "该用户绑定的支付宝账户被冻结或不允许支付";
                    break;
                case 4004:
                    textMsg = "该用户已解除绑定";
                    break;
                case 4005:
                    textMsg = "绑定失败或没有绑定";
                    break;
                case 4006:
                    textMsg = "订单支付失败";
                    break;
                case 4010:
                    textMsg = "重新绑定账户";
                    break;
                case 6000:
                    textMsg = "支付服务正在进行升级操作";
                    break;
                case 6001:
                    textMsg = "已取消支付";
                    break;
                case 0001:
                    textMsg = "缺少商户配置信息,请联系商家";
                    break;
                case 0002:
                    textMsg = "缺少参数,请联系商家";
                    break;
                case 0003:
                    textMsg = "签名错误,请联系商家";
                    break;
            }
            api.toast({
                msg: textMsg
            })
        }
    });

}

//9000：支付成功
//4000：系统异常
//4001：数据格式不正确
//4003：该用户绑定的支付宝账户被冻结或不允许支付
//4004：该用户已解除绑定
//4005：绑定失败或没有绑定
//4006：订单支付失败
//4010：重新绑定账户
//6000：支付服务正在进行升级操作
//6001：用户中途取消支付操作
//0001：缺少商户配置信息（商户id，支付公钥，支付密钥）
//0002：缺少参数（subject、body、amount、tradeNO）
//0003：签名错误（公钥私钥错误）

//支付回调
function notify_url(tradeNO) {
    var url = 'user_ajax.ashx?action=notify_url';
    var data = {};
    data['order_no'] = tradeNO;
    ajaxRequest(url, 'post', data, function (ret, err) {
        // alert(JSON.stringify(ret));
        //关闭到指定窗口，最上面显示的窗口到指定name窗口间的所有窗口都会被关闭
        api.closeToWin({
            name: 'root',
            animation: {
                type: 'flip',
                subType: 'from_bottom',
                duration: 500
            }
        });
    })
}

/******************add by Moqin***********************************************************************************/

/**
 * 添加到localStorage
 * @param storageName名字
 * @param value值
 */
function setLocalStorage(storageName, value) {
    var valueText = localStorage.getItem(storageName);
    if (valueText == null) {
        valueText = value + ",";
    } else {
        valueText += value + ",";
    }
    localStorage.setItem(storageName, valueText)
//            localStorage.removeItem('searchHisroty')
}
/**
 * 获取localstorage,返回一个数组
 * @param storageName名字
 * @returns {*}
 */
function getLocalStorage(storageName, splitText) {
    if (typeof splitText == 'undefined')
        splitText = ","
    var values = localStorage.getItem(storageName);
    if (values == null) {
        return false;
    } else {
        var valueArray = new Array();
        valueArray = values.split(splitText);
        // valueArray=valueArray.trim(valueArray);
        for (var p in valueArray) {
            if (valueArray[p] == 'null' || valueArray[p] == '' || valueArray[p].length == 0) {
                valueArray.splice(p, 1)
            }
        }
        return valueArray;

    }
}
// 字符串变成数组
function toArray(text, splitValue) {
    // alert(text)
    var valueArray = new Array();
    if (typeof splitValue == 'undefined')
        splitValue = ","
    valueArray = text.split(splitValue);
    // valueArray=valueArray.trim(valueArray);
    for (var p in valueArray) {
        if (valueArray[p] == 'null' || valueArray[p] == '' || valueArray[p].length == 0) {
            valueArray.splice(p, 1)
        }
    }
    return valueArray;
}
/**
 * 清除localstorage,参数为空表示清除所有的
 * @param storageName名字
 */
function clearStorage(storageName) {
    if (typeof(storageName) != 'undifined') {
        localStorage.removeItem(storageName);
    } else {
        localStorage.clear();
    }
}
//把时间戳转成时间个2016-12-30 14:36:01 格式  如果没有ymd参数，返回2016-12-30
function stampToTime(stamp, ymd) {
    if (stamp.indexOf("-") < 0) {
        var newDate = new Date();
        newDate.setTime(stamp * 1000);
        var Y = newDate.getFullYear() + "-";
        var M = newDate.getMonth() + 1 < 10 ? "0" + (newDate.getMonth() + 1) + "-" : (newDate.getMonth() + 1) + "-";
        var D = newDate.getDate() + " ";
        var h = newDate.getHours() + ":";
        var m = newDate.getMinutes() + ":";
        var s = newDate.getSeconds();
        if (typeof (ymd) == "undefined") {
            return (Y + M + D + h + m + s);
        } else {
            return (Y + M + D);
        }

    } else {
        return stamp;
    }
}
//其他页面跳转到首页
function goToHome(index) {
    api.execScript({
        name: "root",
        script: 'randomSwitchBtnBakHome(' + index + ')'
    })
    api.closeToWin({
        name: 'root'
    });
}
//订单操作，删除取消时候发送监听，更新数据
function updateOrderNum() {
    api.sendEvent({
        name: "updateOrderNum",
        extra: {
            key: 'true'
        }
    })
}
//关闭frame
function closeFrame() {
    api.closeFrame();
}

// 验证手机号码
function isPhoneNo(tel) {
    var regex = /1[34578]\d{9}$/g;
    if (regex.test(tel)) {
        return true;
    } else {
        return false;
    }
}
function changeNumFormat(num, len) {
    return num.replace(eval('/(\\d{' + len + '})(?=\\d)/g'), "$1 ");
}
//检查身份证
function isCarID(NoId) {
    var isNo = false;
    var isIDCard1 = /^[1-9]\d{7}((0\d)|(1[0-2]))(([0|1|2]\d)|3[0-1])\d{3}$/g;//十五位身份证
    var isIDCard2 = /^[1-9]\d{5}[1-9]\d{3}((0\d)|(1[0-2]))(([0|1|2]\d)|3[0-1])\d{3}([0-9]|(X|x))$/g;//十八位身份证
    if (NoId.length == 15) {
        if (isIDCard1.test(NoId)) {
            isNo = true;
        }
    } else if (NoId.length == 18) {
        if (isIDCard2.test(NoId)) {
            isNo = true;
        }
    }
    return isNo;
}
//跳到聊天http://192.168.3.4/thinkphp/public/index.php/index/User/userInfo/userName/13678970710
//type,有值1表示跟公司聊天
function goToChat(userName, type) {
    var data = {};
    url = "User/userInfo/userName/" + userName;
    ajaxRequest(url, 'get', data, function (ret, err) {
        if (ret.status == 1) {
            var chatName, chatImg, chatId;
            if (type) {
                chatName = ret.msg.company.company;
                chatImg = ret.msg.company.thumb;
                chatId = ret.msg.userid;
            } else {
                chatName = ret.msg.nickname;
                chatImg = ret.msg.head_portrait;
                chatId = ret.msg.userid;
            }
            openchat(chatId, chatImg, chatName, '../', type);
        } else {
            api.toast({
                msg: '聊天失败，请重试',
                duration: 2000,
                location: 'bottom'
            });
        }
    });
}
//提示失败的关闭,定时1.5s后关闭
function failClose(time) {
    if (time == "" || typeof(time) == "undefined") {
        time = 1500;
    }
    setTimeout(function () {
        closeWin();
    }, time)
}
//去掉两边的空格
String.prototype.trim = function () {
    return this.replace(/(^\s*)|(\s*$)/g, '');
}
//加载滚动玩文字
/**
 *
 * @param speed  速度
 * @param oneHeight  一个行的高度
 */
function textMove(element, speed, oneHeight) {
    setInterval(function () {
        var ulHeight = $(element).height();
        var ulMarginTop = $(element).css("margin-top");
        $(element).animate({"margin-top": "-=" + oneHeight + "px"}, 500, function () {
            if (Math.abs(parseInt(ulMarginTop)) >= (ulHeight - oneHeight)) {
                $(element).css({"margin-top": "0"})
            }
        })
    }, speed);
}

//加载滚动玩文字
/**
 *
 * @param speed  速度
 * @param oneHeight  一个行的高度
 */
function textMoveHor(element, speed, oneWidth) {
    var ulWidth = $(element).width();
    setInterval(function () {
        var ulWidth = $(element).width();
        var ulMarginLeft = $(element).css("margin-left");
        $(element).animate({"margin-left": "-=" + oneWidth + "px"}, 500, function () {
            if (Math.abs(parseInt(ulMarginLeft)) >= (ulWidth - oneWidth)) {
                $(element).css({"margin-left": "0"})
            }
        })
    }, speed);
}
function showNoTip(data) {
    if (data == "") {
        $(".kongshuju").show();
    } else {
        $(".kongshuju").hide();
    }
}
function showNoTip1(data) {
    if (data == "") {
        $(".kongshuju1").show();
    } else {
        $(".kongshuju1").hide();
    }
}

// function getUrlParam(url,name) {
//     var reg = new RegExp("(^|&)" + name + "=([^&]*)(&|$)"); //构造一个含有目标参数的正则表达式对象
//     var r="";
//     if(typeof (url)=="undefined"){
//         r = window.location.search.substr(1).match(reg);  //匹配目标参数
//     }else{
//         r=url;
//     }
//
//     if (r != null) return unescape(r[2]); return null; //返回参数值
// }
/**
 *
 * @param url为空时获取当前地址栏的url
 * @param getValueName 为空时候传回全部参数数组
 * @returns {*}
 */
function getUrlParam(url, getValueName) {

    if (typeof (url) == "undefined") {
        url = location.href;
    }
    var result = [];
    var name, value;
    var num = url.indexOf("?")
    url = url.substr(num + 1); //取得所有参数   stringvar.substr(start [, length ]

    var arr = url.split("&"); //各个参数放到数组里
    for (var i = 0; i < arr.length; i++) {
        num = arr[i].indexOf("=");
        if (num > 0) {
            name = arr[i].substring(0, num);
            value = arr[i].substr(num + 1);
//                alert(unescape(value))
            result[name] = value;
//                alert(result[name])
        }
    }
//        for()
    if (typeof (getValueName) != "undefined") {
        return result[getValueName];
    } else {
        return result;
    }

}
//frompage   index
function getQRcode(urlContent, fromPage) {

    getStorageAll();
    // getUserInfo();
    urlContent = urlContent ? "" : "./html/";
    var FNScanner = api.require('FNScanner');
    FNScanner.openScanner({
        autorotation: true
    }, function (ret, err) {
        if (ret) {
            if (ret.eventType == 'success') {
                var url = ret.content;
                var propertyId = getUrlParam(url, "id");
                var propertyName = getUrlParam(url, "nick_name");
                propertyName = decodeURIComponent(propertyName);

                var type = getUrlParam(url, "type");
                //支付
                if ((typeof (propertyId) != "undefined") && (typeof (propertyName) != "undefined")) {
                    //跳去注册页面
                    if (type == "0") {
                        if (fromPage == "index") {
                            api.openWin({
                                name: urlContent + "goToRegister",
                                url: urlContent + "register_win.html",
                                pageParam: {
                                    propertyId: propertyId,
                                    propertyName: propertyName
                                }
                            })
                        } else {
                            api.sendEvent({
                                name: "sendPropertyData",
                                extra: {
                                    propertyId: propertyId,
                                    propertyName: propertyName
                                }
                            })
                        }
                    }

                } else {
                    api.toast({
                        msg: "无效地址！",
                        location: "middle"
                    })
                    return false;
                }
            } else if (ret.eventType == 'selectImage') {
                FNScanner.decodeImg({
                    path: ''
                }, function (ret, err) {
                    if (ret.eventType == 'success') {
                        var url = ret.content;
                        var propertyId = getUrlParam(url, "id");
                        var propertyName = getUrlParam(url, "nick_name");
                        propertyName = decodeURIComponent(propertyName);
                        var type = getUrlParam(url, "type");
                        //支付
                        if ((typeof (propertyId) != "undefined") && (typeof (propertyName) != "undefined")) {
                            //跳去注册页面
                            if (type == "0") {
                                if (fromPage == "index") {
                                    api.openWin({
                                        name: urlContent + "goToRegister",
                                        url: urlContent + "register_win.html",
                                        pageParam: {
                                            propertyId: propertyId,
                                            propertyName: propertyName
                                        }
                                    })
                                } else {
                                    api.sendEvent({
                                        name: "sendPropertyData",
                                        extra: {
                                            propertyId: propertyId,
                                            propertyName: propertyName
                                        }
                                    })
                                }
                            }

                        } else {
                            api.toast({
                                msg: "无效地址！",
                                location: "middle"
                            })
                            return false;
                        }
                    } else {
                        api.toast({
                            msg: "图片识别失败，请重试"
                        })
                    }
                });
            }
        } else {
            api.toast({
                msg: "扫码失败，请重试"
            })
        }
    });

    // FNScanner.decodeImg({
    //     path: ''
    // }, function(ret, err) {
    //     if (ret.status) {
    //         alert(JSON.stringify(ret)+"d");
    //     } else {
    //         alert(JSON.stringify(err)+"e");
    //     }
    // });


}
/**********************************************add to aijiangli***************************************/
function goToWeb(url) {
    api.openWin({
        name: "web",
        url: url
    })
}
function goToGoodInfo(goodId, url) {
    if (typeof (url) == "undefined") {
        url = "";
    }
    api.sendEvent({
        name: "setGoodDataNull",
        extra: {
            key: true
        }
    })
    api.openWin({
        name: "goodsInfo",
        url: url + "goodInfo_win.html",
        pageParam: {
            goodId: goodId
        },
        reload: true
    })
}

function openShopInfo(supplierId) {
    api.openWin({
        name: "shopInfo",
        url: "shopInfo_win.html",
        pageParam: {
            supplierId: supplierId
        }
    })
}
function goToBuy(goodId, type) {
    getStorageAll();
    // user_id=12;
    if (!user_id) {
        api.toast({
            msg: "还没登录,请先登录"
        })
        setTimeout(function () {
            api.openWin({
                name: 'loginPass_win',
                url: 'loginPass_win.html'
            })
        }, 1500)

    } else {
        api.openFrame({
            bgColor: 'rgba(0,0,0,0)',
            name: 'popBuyPage_frm',
            url: 'popBuyPage_frm.html',
            bounces: false,
            rect: {
                x: 0,
                y: 0,
                w: 'auto',
                h: 'auto'
            },
            pageParam: {
                goodId: goodId,
                type: type
            },
            animation: {
                type: "show",                //动画类型（详见动画类型常量）
                subType: "from_bottom",       //动画子类型（详见动画子类型常量）
                duration: 300
            }
        });
    }
}
//打开弹出一个frm的确定页面
// function confirmPage(title,message,callBack) {
function confirmPage(opt) {
    var settings = {
        title: "",
        message: "",
        success: null,
        cancel: null
    }
    opt = $.extend(settings, opt)
    api.openFrame({
        bgColor: 'rgba(0,0,0,0)',
        name: 'popConfirm_frm',
        url: 'popConfirm_frm.html',
        bounces: false,
        rect: {
            x: 0,
            y: 0,
            w: 'auto',
            h: 'auto'
        },
        pageParam: {
            title: opt.title,
            message: opt.message
        }

    });
    var result = false;
    api.addEventListener({
        name: "confirmResult"
    }, function (ret, err) {
        if (ret && ret.value) {
            // result=ret.value.key;
            if (ret.value.key) {
                opt.success()
            } else {
                if (opt.cancel)
                    opt.cancel()
            }
        }
    })

}
function setDataToTamplate(opt) {
    // setDataToTamplate({
    //     apiUrl:"service/category/list",
    //     data:{},
    //     contentElement:"nav-content",
    //     templateElement:"nav-template",
    //     method:"post"
    // })
    var dataInfo = {
        apiUrl: '',
        data: {},
        contentElement: "",
        templateElement: "",
        method: "",
        callBackList: true,
        success: null,
        fail: null

    }
    opt = $.extend(dataInfo, opt);
    // alert(JSON.stringify(opt))
    // alert(JSON.stringify(opt))
    ajaxRequest(opt.apiUrl, opt.method, opt.data, function (ret, err) {
        // alert(JSON.stringify(ret.data))
        if (ret.status == "100") {
            var $content = $("#" + opt.contentElement);
            $content.html('<div class="kongshuju">' +
                // '<img src="../image/not-data.png" style="" >'+
                '<p>暂无数据</p></div>');
            return false;
        }
        var content = $api.byId(opt.contentElement);
        var tpl = $api.byId(opt.templateElement).text;
        var tempFn = doT.template(tpl);
        // alert(JSON.stringify(ret.data))
        $api.html(content, '');
        if (opt.callBackList) {
            $api.html(content, tempFn(ret.msg));
        } else {
            $api.html(content, tempFn(ret.msg));
        }
        if (opt.success) {
            opt.success(ret.msg, err)
        }
    });

}
function whereToGo(userType, urlContent) {
    urlContent = typeof(urlContent) == "undefined" ? "./html/" : "";
    if (userType == "") return false;
    switch (userType) {
        case "user":
            api.closeToWin({
                name: 'root',
                animation: {
                    type: 'flip',
                    subType: 'from_bottom',
                    duration: 500
                }
            });
            break;
        case "supplier":
            if (is_gongyingShang == "1") {
                api.openWin({
                    name: "mineGongyinglian",
                    url: urlContent + "mineGongyinglian.html",
                    slidBackEnabled: false
                })
            } else {
                api.openWin({
                    name: "mineOfSupplier",
                    url: urlContent + "mineOfSupplier.html",
                    slidBackEnabled: false
                })
            }


            break;
        case "agent":
            api.openWin({
                name: "mineOfAgent",
                url: urlContent + "mineOfAgent.html",
                slidBackEnabled: false
            })
            break;

    }
}

//ADDED BY EKIN
function setRefreshControl(opt) {
    var settings = {
        api: '',
        data: {},
        contentElement: '',
        tmplElement: '',
        success: null,
        fail: null,
        refresh: true,
        method: "get"
    }
    opt = $.extend(settings, opt);
    var test = opt;
    // alert(JSON.stringify(opt))
    var $content = $(opt.contentElement);
    var $tpl = $(opt.tmplElement);
    $content.attr('data-page', 1);
    $content.removeAttr('data-lock');
    $content.data('data-opt', opt);
    if (opt.refresh) {
        api.setRefreshHeaderInfo({
            visible: true,
            loadingImg: 'widget://image/ptr_pull.png',
            bgColor: '#efeff4',
            textColor: '#959595',
            textDown: '下拉刷新',
            textUp: '松开刷新',
            showTime: true
        }, function (ret, err) {
            var opt = $content.data('data-opt');
            $content.empty();

            getRefreshControlData(1, $content, $tpl, opt.api, opt.data, opt.success, opt.fail, opt.method);


        });
        api.refreshHeaderLoading();
    } else {
        getRefreshControlData(1, $content, $tpl, opt.api, opt.data, opt.success, opt.fail, opt.method);
    }


    //监听是否达到底部上拉加载
    api.addEventListener({
        name: 'scrolltobottom'
    }, function (ret, err) {
        var dataPage = $content.attr('data-page');
        dataPage++;
        var opt = $content.data('data-opt');
        getRefreshControlData(dataPage, $content, $tpl, opt.api, opt.data, opt.success, opt.fail, opt.method, opt.refresh);
    })
}

function getRefreshControlData(toPage, $content, $tpl, url, data, success, fail, method, refresh) {
    var isLock = $content.attr('data-lock');

    toPage = toPage ? toPage : 1;
    data.page = toPage;
    if (toPage == 1) {
        isLock = false;
        if (refresh) {
            api.refreshHeaderLoading();
        }
    }

    if (!isLock) {
        $content.attr('data-lock', true);

        // alert(JSON.stringify(data))
        ajaxRequest(url, method, data, function (ret, err) {
            $content.attr('data-page', toPage);
            api.refreshHeaderLoadDone();
            var tempFn = doT.template($tpl.text());
            var newHtml = "";
            if (ret.status != "100") {
                newHtml = tempFn(ret.msg);
            }
            if (toPage > 1) {
                if (ret.status == "100") {
                    $content.attr('data-lock', true);
                    return;
                }
                $content.append(newHtml);
            } else {
                if (ret.status == "100") {
                    $content.html('<div class="kongshuju">' +
                        // '<img src="../image/not-data.png" style="" >'+
                        '<p>暂无数据</p></div>');
                } else {
                    $content.html(newHtml);
                }
            }
            if (success) {
                success(ret, err);
            }
            $content.removeAttr('data-lock');
        }, function (ret, err) {
            // alert(JSON.stringify(ret))
            if (fail) {
                fail(ret, err);
            } else {
                api.toast({
                    msg: "请求失败，请稍后重试"
                })
                failClose();
            }

            $content.removeAttr('data-lock');
        });
    }
}


//回复状态栏颜色
function resetStatusbarStyle() {
    api.addEventListener({
        name: 'viewdisappear'
    }, function (ret, err) {
        if (ret) {
            api.setStatusBarStyle({
                style: LAYOUT_STATUSBAR_STYLE
            });
        } else {
        }
    });
}
//跳转到商家
function go2Shop(companyid, path) {
    path = path ? path : './';
    api.openWin({
        name: 'my/myShop_win',
        url: path + 'my/myShop_win.html',
        pageParam: {
            companyid: companyid
        }
    });
    event.preventDefault();
    event.stopPropagation();
}

function go2User(userid, path) {
    path = path ? path : './';
    api.openWin({
        name: 'my/personInfo_win',
        url: path + 'my/personInfo_win.html',
        pageParam: {
            userid: userid
        }
    });
}

//跳转到商品
function go2Pro(itemid, path) {
    path = path ? path : './';
    api.openWin({
        name: 'proInfo_win',
        url: path + 'proInfo_win.html',
        pageParam: {
            itemid: itemid
        }
    });
}

//聊天
function openchat(userid, avatar, name, path, isCompany, itemid) {
    getStorageAll();
    if (user_id == userid) {
        api.toast({msg: '不能和本人聊天'});
    } else {
        path = path ? path : './';
        api.openWin({
            name: 'chat_win',
            url: path + 'userchat/chat_win.html',
            pageParam: {
                targetUserId: userid,
                targetUserAvatar: avatar,
                targetUsername: name,
                isCompany: isCompany,
                itemid: itemid
            }
        });
    }
}
//检查某用户id是否有新信息
function hasNewMsgByUid(targetUserId) {
    var chatContent = $api.getStorage('chatContent');
    if (chatContent) {
        var hasNew = false;
        for (i in chatContent) {
            if (chatContent[i].senderUserId == targetUserId && chatContent[i].unreadCount > 0) {
                hasNew = true;
                break;
            }
        }
        return hasNew;
    }
}

//显示最近时间
function formatMsgTime(timespan) {

    var dateTime = new Date(timespan * 1000);

    var year = dateTime.getFullYear();
    var month = dateTime.getMonth() + 1;
    var day = dateTime.getDate();
    var hour = dateTime.getHours();
    var minute = dateTime.getMinutes();
    var second = dateTime.getSeconds();
    var now = new Date();
    var now_new = Date.parse(now.toDateString());  //typescript转换写法

    var milliseconds = 0;
    var timeSpanStr;

    milliseconds = now_new - timespan;

    if (milliseconds <= 1000 * 60 * 1) {
        timeSpanStr = '刚刚';
    }
    else if (1000 * 60 * 1 < milliseconds && milliseconds <= 1000 * 60 * 60) {
        timeSpanStr = Math.round((milliseconds / (1000 * 60))) + '分钟前';
    }
    else if (1000 * 60 * 60 * 1 < milliseconds && milliseconds <= 1000 * 60 * 60 * 24) {
        timeSpanStr = Math.round(milliseconds / (1000 * 60 * 60)) + '小时前';
    }
    else if (1000 * 60 * 60 * 24 < milliseconds && milliseconds <= 1000 * 60 * 60 * 24 * 15) {
        timeSpanStr = Math.round(milliseconds / (1000 * 60 * 60 * 24)) + '天前';
    }
    else if (milliseconds > 1000 * 60 * 60 * 24 * 15 && year == now.getFullYear()) {
        timeSpanStr = month + '-' + day + ' ' + hour + ':' + minute;
    } else {
        timeSpanStr = year + '-' + month + '-' + day + ' ' + hour + ':' + minute;
    }
    return timeSpanStr;
};


// 支付成功
function comfirmPay(aijiangliOrderId, money) {
    var obj = api.require('aliPay');
    obj.pay({
        partner: '2088421505646281',
        seller: '1832714943@qq.com',
        rsaPriKey: 'MIICeQIBADANBgkqhkiG9w0BAQEFAASCAmMwggJfAgEAAoGBANIcwWGcC3xGaaqlF0fN03/igvdSnOn0hXzqNMdOfqI4X2p9Jsofp05/9q2+OWeNUhzGG3ibCtC9kpqHjaHIJ60O3tyNK+ps8Uu3Kk93eoRWSCstORGmQzTs1SFar23vdzaY9gEwHpYeVG5xwLxkM/3xtruunoks1WbWVEHZ6xYdAgMBAAECgYEArEPvOPwbXpTMZaBdaf2S/jLUdbpB9H8KQtQy2YW9xXq6oDBj8SvqnC3GLcTcg84WGIlEVKmpQGNtI00oDhBwlbJc/wTLw+z/80Ua0IiHiSFZbMfLozParrt4CwMGrjsP18U3+YmzPPlmv58T6vEqPwnpSG59GlUIKn76yZwsHnECQQDqUaggEykxZtm55bpHXDUJCIrdcsAtw2AVifTHQbU0pkkKlNTrmhabJVsYabItjEGnYvlAgneKbxKLaYh1DyRvAkEA5Y22d1/fxzbRyV1BJbZwMNwUGXVsekgiCGkorGyNmB8biXbFYxUJbciZKZCfRsWxaGEgcSusUHWdnHBfN/hsMwJBAKpOOUU+x/TZDSx5FSAim4V6SPvVGGrqkt50y407a8ndhj8Dl5G6B+4xg3lF8TP7ugg//mttqBbczfy38m8qV08CQQC85Q1WVB2IB/M/uS5Hw0W03xTnEjpusXbX5vjiUf1+RXLaflLVQtVccqqeinSWv01KcEpK9j44g2BsAAhKvXEDAkEAgLO7wb9PhosO8eRqmz1SI2on99q1WqHWXeFOBoDTSw7ZWluD6P47KBa5KOqSdO69x426ep0BwcLY9KhIyF9msg==',
        rsaPubKey: 'aliPay_rsaPubKey" value="MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQDSHMFhnAt8RmmqpRdHzdN/4oL3Upzp9IV86jTHTn6iOF9qfSbKH6dOf/atvjlnjVIcxht4mwrQvZKah42hyCetDt7cjSvqbPFLtypPd3qEVkgrLTkRpkM07NUhWq9t73c2mPYBMB6WHlRuccC8ZDP98ba7rp6JLNVm1lRB2esWHQIDAQAB',
        subject: '爱奖励社区', //订单名
        body: '爱奖励社区,订单号:' + aijiangliOrderId, //订单描述
        amount: money, //金额
//            amount: 0.01, //金额
        tradeNO: aijiangliOrderId, //订单编号
        notifyURL: AliPayBack
    }, function (ret, err) {
        if (ret.code == 9000) {
            // finishOrder(aijiangliOrderId)
            api.sendEvent({
                name: 'reGetMyInfo',
                extra: {
                    key: 'true'
                }
            })
            api.toast({
                msg: "支付成功"
            })
            failClose()

        } else {
            //9000：支付成功
            //4000：系统异常
            //4001：数据格式不正确
            //4003：该用户绑定的支付宝账户被冻结或不允许支付
            //4004：该用户已解除绑定
            //4005：绑定失败或没有绑定
            //4006：订单支付失败
            //4010：重新绑定账户
            //6000：支付服务正在进行升级操作
            //6001：用户中途取消支付操作
            //0001：缺少商户配置信息（商户id，支付公钥，支付密钥）
            //0002：缺少参数（subject、body、amount、tradeNO）
            //0003：签名错误（公钥私钥错误）
            var textMsg = "";
            switch (parseInt(ret.code)) {
                case 4000:
                    textMsg = "系统异常";
                    break;
                case 4001:
                    textMsg = "数据格式不正确";
                    break;
                case 4003:
                    textMsg = "该用户绑定的支付宝账户被冻结或不允许支付";
                    break;
                case 4004:
                    textMsg = "该用户已解除绑定";
                    break;
                case 4005:
                    textMsg = "绑定失败或没有绑定";
                    break;
                case 4006:
                    textMsg = "订单支付失败";
                    break;
                case 4010:
                    textMsg = "重新绑定账户";
                    break;
                case 6000:
                    textMsg = "支付服务正在进行升级操作";
                    break;
                case 6001:
                    textMsg = "已取消支付";
                    break;
                case 0001:
                    textMsg = "缺少商户配置信息,请联系商家";
                    break;
                case 0002:
                    textMsg = "缺少参数,请联系商家";
                    break;
                case 0003:
                    textMsg = "签名错误,请联系商家";
                    break;
            }
            api.toast({
                msg: textMsg
            })
        }
    });
}

// 订单完成，支付宝回调方法，或者如果是纯积分，或者全部用了金豆余额的订单处理
function finishOrder(orderId) {
    var data = {};
    data["order_id"] = orderId
//                var url = 'Order/orderStatusModify/userName/'  + user_name + '/orderId/' + orderId + '/status/2/type/1';
    var url = 'order/pay';
    ajaxRequest(url, 'post', data, function (ret, err) {
        api.toast({
            msg: "支付成功"
        })
        failClose()
    })
}
// 先下支付，商家录单和扫码
function comfirmPayOffline(money, supplier_id, mobile, cashback_type_id, type) {
    var text = type == "1" ? "录单支付" : "扫码支付";
    var obj = api.require('aliPay');
    obj.pay({
        partner: '2088621729976782',
        seller: '384882776@qq.com',
        rsaPriKey: 'MIICeAIBADANBgkqhkiG9w0BAQEFAASCAmIwggJeAgEAAoGBAOU2tylDHcnDw8KNrd6sfcxNHtAaiRjre3ONUliP2EGnepxUUS8WC5D6ZjkreyydiVGdYvYD/ZMFQfbKuEen9nZi0jJ7pQmNqZaVwlYhAj3LJa2Yq19TIJNjUjcnOq02faIR0f5BVpdTUPvRvA1966KFAh7zELJf4/vMdBxU6p0TAgMBAAECgYEAm04gene8VjoriMYgedDcB7J1X0GrhNQBOIEXu2PzfkCxJf1HaKUCP0A6RSA9/DPdmAwQwmpfxN76G/KtO/gFWFcxmcjv6vYnjfw7yMVDwP2vvWKKjp3pD59UfvWBzJEDFHAImqxrxAFSjoZS6OKkLAudnMHGoAlUfGoiwxLTT6ECQQD31Bmwe46Eew7mqKWj//AAWjiKXZ0pzK3hWBZ2TEGuhHbCKU3CjaUdEEypkADbzQmsf1lB2ICPODMnu71kUXORAkEA7MV9QloNY4GyYDqngYgWc0Uy5M6IbsDL5w/a0WJyx2ujhNp6ihUAu9a18XJzpZ/XW65ElIqndVZIZRP7ra4sYwJBAPXyAPia9gnV0ijor1G9OmIvJzNxyfnkjZ83+zq1XO2jufPgZ7IvPfBE77/LEH8R0Yrl6x+ki5kWjfXdpAv9pXECQCfIt1di0kUaEeLheCvntf4AbqDLo1kYxCo7G8V7CVZA2+UC4Pw6szjcxw2e8Zeu1/zrt1JOSf0JVnjFdtCkJ4kCQQCF4oT23r80PX0ewkiqylcDlqTN2enp5ksz6c/eMDOqVVKB6FJTY4lcU6t6Kpc/xj6joD6p6S2zhGlXdTlYdYuG',
        rsaPubKey: 'MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQDlNrcpQx3Jw8PCja3erH3MTR7QGokY63tzjVJYj9hBp3qcVFEvFguQ+mY5K3ssnYlRnWL2A/2TBUH2yrhHp/Z2YtIye6UJjamWlcJWIQI9yyWtmKtfUyCTY1I3JzqtNn2iEdH+QVaXU1D70bwNfeuihQIe8xCyX+P7zHQcVOqdEwIDAQAB',
        subject: text, //订单名
        body: text, //订单描述
        amount: money, //金额
//            amount: 0.01, //金额
        tradeNO: Date.parse(new Date()), //订单编号
        notifyURL: serverUrl + 'Order/aliNotify'
    }, function (ret, err) {
        if (ret.code == 9000) {
            var data = {};
            data["amount"] = money;
            data["supplier_id"] = supplier_id;
            data["mobile"] = mobile;
            data["cashback_type_id"] = cashback_type_id;
            data["type"] = type;
            // alert(JSON.stringify(data))
//                var url = 'Order/orderStatusModify/userName/' + user_name + '/orderId/' + orderId + '/status/2/type/1';
            var url = 'order/offline_pay';
            ajaxRequest(url, 'post', data, function (ret, err) {
                api.toast({
                    msg: "支付成功"
                })
                failClose()
            })
        } else {
            var textMsg = "";
            switch (parseInt(ret.code)) {
                case 4000:
                    textMsg = "系统异常";
                    break;
                case 4001:
                    textMsg = "数据格式不正确";
                    break;
                case 4003:
                    textMsg = "该用户绑定的支付宝账户被冻结或不允许支付";
                    break;
                case 4004:
                    textMsg = "该用户已解除绑定";
                    break;
                case 4005:
                    textMsg = "绑定失败或没有绑定";
                    break;
                case 4006:
                    textMsg = "订单支付失败";
                    break;
                case 4010:
                    textMsg = "重新绑定账户";
                    break;
                case 6000:
                    textMsg = "支付服务正在进行升级操作";
                    break;
                case 6001:
                    textMsg = "已取消支付";
                    break;
                case 0001:
                    textMsg = "缺少商户配置信息,请联系商家";
                    break;
                case 0002:
                    textMsg = "缺少参数,请联系商家";
                    break;
                case 0003:
                    textMsg = "签名错误,请联系商家";
                    break;
            }
            api.toast({
                msg: textMsg
            })
        }
    });
}

function showLoadingMo(title) {
    if (typeof (title) == "undefined" || title == "") {
        title = "加载中"
    }
    api.showProgress({
        style: 'default',
        animationType: 'fade',
        title: title + '...',
        text: '',
        modal: true
    });
}
function hideLoadingMo() {
    api.hideProgress();
}
function goToAdv(obj) {
    var type = $(obj).attr("data-type");
    var id = $(obj).attr("data-id");
    if (type == "1") {
        //单个页面：类似关于我们
        api.openWin({
            name: "goToAdv3",
            url: "advInfo_win.html",
            pageParam: {
                advId: id
            }
        })
    } else if (type == "2") {
//类似商品详情
        goToGoodInfo(id)
    } else if (type == "3") {
        //指定类别
        goToGoodList(id, 7);
    }
}

function goToGoodList(id, channelId) {
    // alert(id)
    api.openWin({
        name: "goToGoodList",
        url: "categoryThree_win.html",
        pageParam: {
            id: id,
            channelId: channelId
        }
    })
}

function showLoadingMo2(title) {
    $("body").append("<div id='loadedCount' data-count='1'></div>");
    if (typeof (title) == "undefined" || title == "") {
        title = "加载中"
    }
    api.showProgress({
        style: 'default',
        animationType: 'fade',
        title: title + '...',
        text: '',
        modal: true
    });
}
function hideLoadingMo2(totalCount) {
    var count = parseInt($("#loadedCount").attr("data-count"));
    if (count == totalCount) {
        api.hideProgress();
        $("#loadedCount").remove();
    } else {
        count++;
        $("#loadedCount").attr("data-count", count);
    }
}

function showEchoImg() {
    echo.init({
        offset: 0,
        throttle: 0
    });
}
function touchMove(callBack){
    var startX, startY, moveEndX, moveEndY, X, Y,result,time1,time2;
    $("body").on("touchstart", function(e) {
        // e.preventDefault();
        time1=new Date().getTime();
        startX = e.originalEvent.changedTouches[0].pageX,
            startY = e.originalEvent.changedTouches[0].pageY;
    });
    $("body").on("touchmove", function(e) {
        // e.preventDefault();
        moveEndX = e.originalEvent.changedTouches[0].pageX,
            moveEndY = e.originalEvent.changedTouches[0].pageY,
            X = moveEndX - startX,
            Y = moveEndY - startY;


        if( Math.abs(X) > Math.abs(Y) && X > 0 ) {
            result="l2r";
            // alert(result)
        }else if
        ( Math.abs(X) > Math.abs(Y) && X < 0 ) {
            result="r2l";
            // alert(result)
        }else if
        ( Math.abs(Y) > Math.abs(X) && Y > 0) {
            result="t2b";
            // alert(result)
        }else if( Math.abs(Y) > Math.abs(X) && Y < 0 ) {
            result="b2t";
            // alert(result)
        } else{
            result="touch";
        }
        time2=new Date().getTime();

    });
    $("body").on("touchend", function(e) {
        if(callBack){
            callBack(result,time2-time1)
        }
    })
}